const { Param, Db, Ret } = require("@less-is-more/less-js");
const dayjs = require("dayjs");
const <%= modelName %> = require("../model/<%= modelFileName%>");

module.exports = class <%= modelName %>Controller {
  async add(req, res) {
    let data = req.params;
    let params = await Param.checkParams([
    <%_ attrs.forEach((n) => { _%>
      <%_ if(n != "id") { _%>
      ["<%= n %>", data.<%= n %>, "require", "请正确输入<%= n %>"],
      <%_ } _%>  
    <%_ }) _%>  
    ]);
    await Db.add(<%= modelName %>, params);
    return new Ret(true);
  }

  async update(req, res) {
    let data = req.params;
    let params = await Param.checkParams([
    <%_ attrs.forEach((n) => { _%>
      ["<%= n %>", data.<%= n %>, "require", "请正确输入<%= n %>"],
    <%_ }) _%>  
    ]);
    await Db.update(<%= modelName %>, params, {
      id: params.id,
    });
    return new Ret(true);
  }

  async batchDel(req, res) {
    let params = await Param.checkParams([
      ["ids", req.params.ids, "require", "请正确输入编号"],
    ]);
    await Db.sql(
      "delete from <%= modelFileName %> where id in (?)",
      [params.ids.split(",")],
      Db.SQL_TYPE_DELETE
    );
    return new Ret(true);
  }

  async list(req, res) {
    let data = req.params;
    let search = await Param.checkParams([
    <%_ attrs.forEach((n) => { _%>
      ["<%= n %>", data.<%= n %>, "require", "请正确输入<%= n %>"],
    <%_ }) _%>  
      ["page", data.page, "isInt require", "请正确输入页数"],
      ["time", data.time, "isInt", "请正确输入分页时间"],
    ]);

    let timeArray = [{ [Db.Op.lt]: new Date(parseInt(data.time)) }];
    if (!Param.isBlank(search.startCreateTime)) {
      const startCreateTime = new dayjs(
        search.startCreateTime,
        "YYYY-MM-DD HH:mm:ss"
      ).toDate();
      timeArray.push({ [Db.Op.gt]: startCreateTime });
    }
    if (!Param.isBlank(search.endCreateTime)) {
      const endCreateTime = new dayjs(
        search.endCreateTime,
        "YYYY-MM-DD HH:mm:ss"
      ).toDate();
      timeArray.push({ [Db.Op.lte]: endCreateTime });
    }
    search.createTime = {
      [Db.Op.and]: timeArray,
    };

    let pageNum = search.page;
    delete search.page;
    let result = await Db.find(<%= modelName %>, search, [["id", "desc"]], pageNum);
    return new Ret(true).setData({ total: result.count, list: result.rows });
  }
};
